import UIView from "../../core/mvcFrame/view/UIView";
import {
    UIViewPanelGameListViewMsg,
    UIViewPanelPopupWindowMsg,
    UIViewPanelRankViewMsg, UIViewPanelWheelLuckyViewMsg,
    UIViewSceneGameMsg
} from "../../eventMsg/AllEventMsg";
import TMessage from "../../core/mvcFrame/TMessage";
import SceneLogin from "./SceneLogin";
import PanelPopupWindow from "../panels/common/PanelPopupWindow";
import PanelRankView from "../panels/rank/PanelRankView";
import PanelGameList from "../panels/gameList/PanelGameList";
import PanelWheelLuckyView from "../panels/wheelLucky/PanelWheelLuckyView";
import {CCLabel} from "../../core/base/CCComponent";
import SpriteFrameAnimationComponent from "../../core/components/SpriteFrameAnimationComponent";
import EnemyRole from "./game/EnemyRole";
import BaseBoxCollider from "../../core/components/BaseBoxCollider";

const {ccclass, property} = cc._decorator;
/*
*ClassName:SceneGame
*Description:TODO
*Date:2019/10/26 1:00
*/
@ccclass
export default class SceneGame extends UIView {

    protected static prefabUrl = "prefabs/scenes/SceneGame";
    protected static className = "SceneGame";

    @property(cc.Node)
    game_node: cc.Node = null;
    //我方英雄组件
    @property(cc.Node)
    heroNode: cc.Node = null;
    @property(cc.Node)
    shootLineImg: cc.Node = null;
    @property(cc.Node)
    myBulletImg: cc.Node = null;
    @property(cc.Node)
    myHeroImg: cc.Node = null;
    @property(cc.Node)
    myGunImg: cc.Node = null;
    @property(cc.Node)
    shieldImg: cc.Node = null;
    @property(cc.ProgressBar)
    bloodBar: cc.ProgressBar = null;
    @property(cc.ParticleSystem)
    heroDieParticle: cc.ParticleSystem = null;

    //得分
    @property(cc.Label)
    txt_score: cc.Label = null;

    @property([cc.Prefab])
    myBulletPrefab: cc.Prefab[] = [];

    @property(cc.Prefab)
    enemyPrefab: cc.Prefab = null;

    _winSize = null;
    _canShooting = false;
    _canContact = false;
    _curScore = 0;
    _heroBloodValue = 100;

    heroType = 1;//角色类型

    enemyNode: EnemyRole = null;

    _curAngle: number = 42;


    bulletNode: cc.Node = null;
    bulletfun = null;

    @property(cc.Node)
    bulletSpNode :cc.Node = null;

    onLoad() {
        super.onLoad();

        this._winSize = cc.winSize;
        this._canShooting = true;  //是否能射击
        this._canContact = true;   //是否检测碰撞
        this._curScore = 0;  //当前得分
        this._heroBloodValue = 100;  //当前血量值

        //打开物理系统
        cc.director.getPhysicsManager().enabled = true;
        //cc.director.getPhysicsManager().debugDrawFlags = true;

        // 重力加速度的配置
        cc.director.getPhysicsManager().gravity = cc.v2(0, -640);

        //我方英雄等待动作
        this.myHeroAni(false);

        //创建敌人
        this.createEnemy();

        //地方英雄等待动画
        this.enemyNode.enemyAni();
    }

    Show(msg: UIViewSceneGameMsg = null) {
        super.Show(msg);

        console.log("主场景");
        // TMessage.NotifyShowUI(PanelPopupWindow, new UIViewPanelPopupWindowMsg());
    }

    //进入主场景
    public OnBtnClickGoToSceneLogin() {
        //TMessage.NotifyShowUI(PanelPopupWindow, new UIViewPanelPopupWindowMsg());
        //TMessage.NotifyShowScene(SceneLogin);

        TMessage.NotifyShowUI(PanelPopupWindow, new UIViewPanelPopupWindowMsg());
    }

    public OnBtnClickOpenRank() {

        TMessage.NotifyShowUI(PanelRankView, new UIViewPanelRankViewMsg());
    }

    public OnBtnClickOpenGameList() {

        TMessage.NotifyShowUI(PanelGameList, new UIViewPanelGameListViewMsg());
    }

    public OnBtnClickOpenWheelLucky() {

        TMessage.NotifyShowUI(PanelWheelLuckyView, new UIViewPanelWheelLuckyViewMsg());
    }

    public OnBtnClickStartGame() {

        this.updateGunAngle();
    }

    // createBullet () {
    //     // 设置精灵位置
    //     this.bulletSpNode.position = cc.v2(50, 50);
    //     // 抛物线运动
    //     this.bulletSpNode.runAction(cc.spawn(cc.rotateBy(1, 360),this.create(1, cc.v2(50, 50), cc.v2(450, 50), 100, 60)));
    //
    //     this.bulletNode.runAction(cc.moveBy(3,this.bulletNode.x + 300,this.bulletNode.y + 200));
    // }

    // 抛物线创建
    create1(t, startPoint, endPoint, height, angle) {
        // 把角度转换为弧度
        let radian = angle * 3.14159 / 180;
        // 第一个控制点为抛物线左半弧的中点
        let q1x = startPoint.x + (endPoint.x - startPoint.x) / 4;
        let q1 = cc.v2(q1x, height + startPoint.y + Math.cos(radian) * q1x);
        // 第二个控制点为整个抛物线的中点
        let q2x = startPoint.x + (endPoint.x - startPoint.x) / 2;
        let q2 = cc.v2(q2x, height + startPoint.y + Math.cos(radian) * q2x);
        // 曲线配置
        return cc.bezierTo(t, [q1, q2, endPoint]).easing(cc.easeInOut(0.5));
    }
    create(t, startPoint, endPoint, height, angle) {
        // 把角度转换为弧度
        let radian = angle * 3.14159 / 180;
        // 第一个控制点为抛物线左半弧的中点
        let q1x = startPoint.x + (endPoint.x - startPoint.x) / 4;
        let q1 = cc.v2(q1x, height + startPoint.y + Math.cos(radian) * q1x+200);
        // 第二个控制点为整个抛物线的中点
        let q2x = startPoint.x + (endPoint.x - startPoint.x) / 2;
        let q2 = cc.v2(q2x, height + startPoint.y + Math.cos(radian) * q2x);

        // 曲线配置
        // return cc.bezierTo(t, [q1, q2, endPoint]);
        // 曲线配置
        return cc.bezierTo(t, [q1, q2, endPoint]);
    }

    //更新炮管角度
    updateGunAngle() {
        // this.shootLineImg.active = true;
        this.myGunImg.angle = this._curAngle;

        // this.setBulletBody();
        // this.schedule(this.create1,0.5,cc.macro.REPEAT_FOREVER,1);
        this.bulletSpNode.angle = this._curAngle;
        this.bulletSpNode.position = cc.v2(-550,-75+20);
        this.bulletSpNode.runAction(this.create(2, cc.v2(50, 50), cc.v2(300, -75), 30, 60));
        //
        let curPos = this.bulletSpNode.position;
        let lastPos = curPos;
        this.bulletfun1 = function () {
            curPos = this.bulletSpNode.position;
            //计算角度
            let lenX = curPos.x - lastPos.x;
            let lenY = 0;
            let r = 0;
            if (curPos.y < lastPos.y) { //向上运动
                lenY = curPos.y - lastPos.y;
                r = Math.atan2(lenY, lenX) * 180 / Math.PI;
            } else {   //向下运动
                lenY = lastPos.y - curPos.y;
                r = -1 * Math.atan2(lenY, lenX) * 180 / Math.PI;
            }
            lastPos = curPos;
            this.bulletSpNode.angle = r;
        };
        this.schedule(this.bulletfun1, 0.1);

        // this.fly = true;

        this.onEventAutoShoot();
    }

    fly = false;
    v_x = 10;
    v_y = 2;
    protected update(dt: number): void {
        // if(this.fly){
        //     this.bulletSpNode.x +=this.v_x*dt ;
        //     this.v_y-=500*dt;
        //     this.bulletSpNode.y+=this.v_y * dt;
        // }
    }

    bulletfun1=null;
    //停止更新炮管
    stopGunAngle() {
        // this.shootLineImg.active = false;
    }

    onEventAutoShoot() {
        if (!this._canShooting) {
            return;
        }
        cc.log("onEventEnd");

        this._canShooting = false;
        this.stopGunAngle();
        this.setBulletBody();

        let x = 10000;
        //2号子弹体积较大，需要更大的力
        if (this.heroType == 1) {
            x = 7000;
        }
        //通过角度计算力度
        let y = x * Math.tan(Math.abs(this._curAngle) * (Math.PI / 180));
        //给子弹设置冲量
        this.bulletNode.getComponent(cc.RigidBody).applyForceToCenter(cc.v2(x, y),false);

        let curPos = this.bulletNode.position;
        let lastPos = curPos;
        this.bulletfun = function () {
            curPos = this.bulletNode.position;
            //计算角度
            let lenX = curPos.x - lastPos.x;
            let lenY = 0;
            let r = 0;
            if (curPos.y < lastPos.y) { //向上运动
                lenY = curPos.y - lastPos.y;
                r = Math.atan2(lenY, lenX) * 180 / Math.PI;
            } else {   //向下运动
                lenY = lastPos.y - curPos.y;
                r = -1 * Math.atan2(lenY, lenX) * 180 / Math.PI;
            }
            lastPos = curPos;
            this.bulletNode.angle = r;
        };
        this.schedule(this.bulletfun, 0.1);

        // this.scheduleOnce(()=>{
        //     this.myGunImg.angle = 0;
        // },0.3)
    }

    //给自己的子弹绑定刚体
    setBulletBody() {
        //创建子弹
        this.bulletNode = cc.instantiate(this.myBulletPrefab[this.heroType]);
        this.bulletNode.parent = this.myGunImg;
        this.bulletNode.position = this.myBulletImg.position;
        let bulletSp = this.bulletNode.getComponent(BaseBoxCollider);
        bulletSp.contactCallBack((selfCollider, otherCollider) => {
            if (!this._canContact) {
                return;
            }
            //this.playSound("sound/openFire", false);
            this._canContact = false;
            //停止子弹监听
            this.unschedule(this.bulletfun);

            let bodyGroup0 = selfCollider.node.group;
            let bodyGroup1 = otherCollider.node.group;

            //子弹打到地面
            if ((bodyGroup0 == "playerBullet" && bodyGroup1 == "floor")
                || (bodyGroup0 == "floor" && bodyGroup1 == "playerBullet")) {
                this.node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(() => {
                    this.bulletNode.removeFromParent();
                    this.bulletNode = null;
                    this.enemyOpenFire();
                })));
            }

            //子弹打到柱子
            if ((bodyGroup0 == "playerBullet" && bodyGroup1 == "column")
                || (bodyGroup0 == "column" && bodyGroup1 == "playerBullet")) {
                this.node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(() => {
                    this.bulletNode.removeFromParent();
                    this.bulletNode = null;
                    this.enemyOpenFire();
                })));
            }

            //子弹打到敌人
            if ((bodyGroup0 == "playerBullet" && bodyGroup1 == "enemy")
                || (bodyGroup0 == "enemy" && bodyGroup1 == "playerBullet")) {
                this.enemyNode.enemyDie();
                this.node.runAction(cc.sequence(cc.delayTime(0.3), cc.callFunc(() => {
                    this.bulletNode.removeFromParent();
                    this.bulletNode = null;
                    this.updateScore();
                    this.myHeroAni(true);
                    this.myHeroScaleAni();
                    // this.gameBgAni();
                    this.enemyNode.enemyMove();
                })));
            }
        });
    }

    //创建敌人
    createEnemy() {
        let node = cc.instantiate(this.enemyPrefab);
        node.parent = this.game_node;
        node.position = cc.v2(300, -100);
        this.enemyNode = node.getComponent(EnemyRole);
        this.enemyNode.comeOnAni();
        console.log(node.position);
        this.enemyNode.finishCallBack(() => {
            //可检测碰撞
            this._canContact = true;
            //设置为可发炮
            this._canShooting = true;
            // node.destroy();
            // node = null;
            this.enemyNode.node.destroy();
            this.createEnemy();

        });
        this.enemyNode.hitHeroCallBack(() => {
            this._heroBloodValue = this._heroBloodValue - 5;
            if (this._heroBloodValue <= 0) {
                //this.playSound("sound/heroDie", false);
                this._heroBloodValue = 0;
                this.myHeroDie();
                //显示结算界面
                //this.gameOver();
            } else {
                //this.playSound("sound/enemyDie", false);
                this.setBloodValue();

                //还原炮的角度
                this.myGunImg.angle = 0;

                //设置为允许开炮
                this._canShooting = true;
                this._canContact = true;
            }
        });
    }

    //敌方开炮
    enemyOpenFire() {
        //敌方子弹世界坐标
        let enemyBulletPos = this.enemyNode.enemyBulletWorldPos();
        //我方英雄世界坐标
        let myHeroPos = this.myHeroImg.parent.convertToWorldSpaceAR(cc.v2(this.myHeroImg.position.x, this.myHeroImg.position.y + 30));

        //计算夹角
        let lenX = Math.abs(enemyBulletPos.x - myHeroPos.x);
        let lenY = Math.abs(enemyBulletPos.y - myHeroPos.y);
        let angle = Math.atan2(lenY, lenX) * 180 / Math.PI;

        //设置敌方小火炮的角度
        this.enemyNode.setGunAngle(angle);

        //计算炮运行的距离
        let len = Math.sqrt(Math.pow(lenX, 2) + Math.pow(lenY, 2));
        this.enemyNode.gunAni(len);
        // this.playSound("sound/enemyBullet", false);
    }

    //我方英雄运动
    myHeroAni(isRun: boolean) {
        if (isRun) {
            this.myHeroImg.getComponent(SpriteFrameAnimationComponent).playAni("heroRun" + this.heroType + "_", 5, 0.06, true);
        } else {
            this.myHeroImg.getComponent(SpriteFrameAnimationComponent).playAni("heroWait" + this.heroType + "_", 3, 0.1, true);
        }
    }

    //我方英雄死亡动画
    myHeroDie() {
        this.heroDieParticle.node.active = true;
        this.heroDieParticle.stopSystem();
        this.heroDieParticle.resetSystem();
        //隐藏我方英雄
        this.heroNode.active = false;
    }

//我方英雄缩放效果
    myHeroScaleAni() {
        this.heroNode.runAction(cc.sequence(cc.scaleTo(1.0, 1.1), cc.scaleTo(1.0, 1.0)));
    }


    //刷新英雄的血量
    setBloodValue() {
        //设置盾牌透明度
        let p = this._heroBloodValue / 100;
        this.shieldImg.opacity = Math.floor(p * 255);
        //设置血量进度
        this.bloodBar.progress = p;
    }

    //刷新得分
    updateScore() {
        this._curScore += 1;
        this.txt_score.string = this._curScore.toString();
        // this.playSound("sound/addScore", false);
    }
}